package com.core.utils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.TableMapping;

public class ModelDb extends Db {
	
	/**
	 * 批量执行sql,以 ";"隔开
	 */
	public static int[] batch(String sql , int batchSize){
		if (StrKit.notBlank(sql)) {
			String[] arr = sql.split(";");
			List<String> sqlList = Arrays.asList(arr);
			return batch(sqlList, batchSize);//size条一提交
		}
		return new int[0];
	}
	
	/**
	 * 批量保存
	 */
	@SuppressWarnings("rawtypes")
	public static int[] batchSave(Class<? extends Model> modelClass,List<Map<String, Object>> dataList) {
        return batchSave(modelClass,dataList,dataList.size());
    }
	
	@SuppressWarnings("rawtypes")
	public static boolean save(Class<? extends Model> modelClass,Map<String,Object> modelMap) {
		String tableName = TableMapping.me().getTable(modelClass).getName();
		Record record = new Record();
		record.setColumns(modelMap);
		return save(tableName, record);
	}
	
	/**
	 * 批量保存
	 */
    @SuppressWarnings("rawtypes")
    public static int[] batchSave(Class<? extends Model> modelClass, List<Map<String, Object>> dataList, int batchSize) {
    	if(dataList.isEmpty())
    		return null;
    	Map<String, Object> attrs = dataList.get(0);
    	StringBuilder sql = new StringBuilder();
    	List<Object> paras = Lists.newArrayList();
    	DbKit.getConfig().getDialect().forModelSave(TableMapping.me().getTable(modelClass), attrs, sql, paras);
       
    	Object[][] batchPara = new Object[dataList.size()][attrs.size()];
        for (int i = 0; i < dataList.size(); i++) {
            int j = 0;
            for (String key : attrs.keySet()) {
                batchPara[i][j++] = dataList.get(i).get(key);
            }
        }
        return batch(sql.toString(), batchPara, batchSize);
    }
}
